package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.LoginDataBean;
import com.fancy.learncenter.bean.TokenDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.RSA;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.tel_edit)
    EditText telEdit;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.login_bt)
    Button loginBt;
    @Bind(R.id.regsiter_bt)
    TextView regsiterBt;
    @Bind(R.id.forget_tv)
    TextView forgetTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login, Status.STATUS);
        ButterKnife.bind(this);
        getToken();


        if (!TextUtils.isEmpty(LoginUserSharePrefernce.getMobile()) && !TextUtils.isEmpty(LoginUserSharePrefernce.getPassword())) {

            telEdit.setText(LoginUserSharePrefernce.getMobile());

            passwordEdit.setText(LoginUserSharePrefernce.getPassword());

        }


    }

    @OnClick({R.id.login_bt, R.id.regsiter_bt, R.id.back_image, R.id.forget_tv, R.id.account_delete, R.id.password_delete})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.login_bt:
                login();
                break;
            case R.id.regsiter_bt:
                intent = new Intent(this, RegsiterActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.forget_tv:
                intent = new Intent(this, ForgetPSWActivity.class);
                startActivity(intent);
                break;
            case R.id.account_delete:
                telEdit.setText("");
                break;
            case R.id.password_delete:
                passwordEdit.setText("");
                break;
            case R.id.back_image:
                finish();
                break;
        }
    }

    private void login() {

        if (!Utils.isMobileNO(telEdit.getText().toString())) {
            ToastUtil.show("请输入正确的手机号");
            return;
        }
        if (TextUtils.isEmpty(passwordEdit.getText())) {
            ToastUtil.show("请输入密码");
            return;
        }
        String rsaStr = "";
        try {
            rsaStr = RSA.ecrypt(Constant.loginToken + passwordEdit.getText().toString(), Constant.RSA_PUBLIC_KEY, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("password", rsaStr);
        map.put("mobile", telEdit.getText().toString());
        HttpMehtod.getInstance().login(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                //解析数据
                BaseBean<LoginDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), LoginDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<LoginDataBean>() {
                    @Override
                    public void success(LoginDataBean dataBean) {

                        Constant.isLogin = true;

                        LoginUserSharePrefernce.putCustomId(dataBean.getLoginUser().getCustomerId());
                        LoginUserSharePrefernce.putHeaderPath(dataBean.getLoginUser().getHeaderImageUrl());
                        LoginUserSharePrefernce.putMobile(dataBean.getLoginUser().getMobile());
                        LoginUserSharePrefernce.putPassword(passwordEdit.getText().toString());
                        LoginUserSharePrefernce.putName(dataBean.getLoginUser().getNickname());
                        LoginUserSharePrefernce.putFid(dataBean.getLoginUser().getFancyId());
                        LoginUserSharePrefernce.putToken(dataBean.getLoginUser().getToken());
                        LoginUserSharePrefernce.update(true);
                        LoginUserSharePrefernce.login(true);

                        JPushInterface.setAlias(LoginActivity.this, 1, dataBean.getLoginUser().getMobile());

                        LoginMall();


                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra(MainActivity.START_KEY, MainActivity.NGK_CODE);
                        startActivity(intent);


                        finish();
                    }

                    @Override
                    public void fail(String errorCode) {
                        LoginUserSharePrefernce.clearData();
                    }

                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                LoginUserSharePrefernce.clearData();
            }
        });
    }

    //商城登录
    private void LoginMall() {
        WebView mWebView = (WebView) findViewById(R.id.login_webview);
        String url = Constant.getMallLoginUrl();
        String fid = LoginUserSharePrefernce.getFid();
        String token = LoginUserSharePrefernce.getToken();

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        try {
            sbUrl.append("&fid=").append(fid)
                    .append("&token=").append(token)
                    .append("&location=").append(URLEncoder.encode("无城市", "utf-8"))
                    //用户看到的版本号
                    .append("&userVs=").append(Utils.getVersionName())
                    // 手机更新迭代次数
                    .append("&developVs=").append(Utils.getVersionCode())
                    .append("&pushToken=").append(URLEncoder.encode("无参数", "utf-8"))
                    //   操作系统
                    .append("&os=").append("Android")
                    //   系统版本号
                    .append("&osVs=").append(Build.VERSION.RELEASE)
                    //   手机型号
                    .append("&deviceType=").append(Build.MODEL)
                    //   手机唯一识别码
                    .append("&deviceUtdid=").append(URLEncoder.encode("无参数", "utf-8"))
                    .append("&keyFrom=").append(Constant.KEY_FR0M)
                    .append("&fromApp=").append(URLEncoder.encode("环球少年", "utf-8"));

        } catch (Exception e) {
            e.printStackTrace();
        }

        CookieManager cookieManager = CookieManager.getInstance();
        String CookieStr = cookieManager.getCookie(sbUrl.toString());
        cookieManager.removeAllCookie();

        mWebView.loadUrl(sbUrl.toString());
    }

    @Override
    public void finish() {
        setResult(Constant.FRESH_RESULT_CALLBACK);
        super.finish();
    }


    private void getToken() {
        HttpMehtod.getInstance().getToken(new CustomNetSubscriber(this, false) {

            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<TokenDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), TokenDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<TokenDataBean>() {
                    @Override
                    public void success(TokenDataBean dataBean) {
                        Constant.loginToken = dataBean.getLoginToken();
                        Constant.JSESSIONID = dataBean.getJSESSIONID();

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).customDealData();

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }

}
